<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃      
 * Date: 2015-09-09
 */
namespace Admin\Controller;
use Home\Logic\MoneyLogLogic;
use Think\AjaxPage;
use Think\Page;

class RebateConfigController extends BaseController {



    protected  $config = array();
    protected  $tree = array();
    protected  $rebate = 0; //总销售额返利比例
    protected  $selfRebate = 0; //自身销售额返利比例
    protected  $rebateMoney = 0; //返利金额
    public function __construct()
    {
        parent::__construct();
        $conf = M('RebateConfig')->order('start_money  desc')->select();
        foreach ($conf as $key => $val){
            $this->config[$val['start_money']] = $val['rebate_ratio'];
        }
    }

    /**
     *  代理商返利规则列表
     */
    public function rebateConfigList(){
        $this->display('rebateConfigList');
    }


    /**
     *  代理商返利规则列表
     */
    public function ajaxRebateConfigList(){

        $where = ' 1 = 1 '; // 搜索条件

        $region_id = I('post.region_id');


        if($region_id > 0)
        {
            $where .= "and  ( region_id = " . $region_id . " )";
        }

        $model = M('RebateConfig');
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);


        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)
            ->order($order_str)
            ->limit($Page->firstRow.','.$Page->listRows)->select();
//        foreach ($goodsList as $key => $val){
//
//            $goodsList[$key]['region_name'] = M('region')->where(array('id'=>$val['region_id']))->getField('name');
//
//        }


        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }




    /**
     * 添加修改代理商返利规则
     */
    public function addEditRebateConfig()
    {

        $Goods = D('RebateConfig'); //
        $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新

        //ajax提交验证
        if (($_GET['is_ajax'] == 1) && IS_POST) {

            C('TOKEN_ON', false);
            if (!$Goods->create(I('post.'), $type))// 根据表单提交的POST数据创建数据对象
            {
                //  编辑
                $error = $Goods->getError();
                $this->ajaxReturn(array('type'=> $error));
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn(json_encode($return_arr));
            } else {
                //  form表单提交
                //$Goods->cat_id = $_POST['cat_id_1'];
//                $Goods->region_id = $_POST['region_id'];
//                $this->ajaxReturn($type);
                if ($type == 2) {
                    $goods_id = $_POST['id'];
                    $Goods->save(); // 写入数据到数据库
                } else {
                    $goods_id = $insert_id = $Goods->add(); // 写入数据到数据库
                }

                $return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/RebateConfig/rebateConfigList')),
                );
                $this->ajaxReturn(json_encode($return_arr));
            }
        }

        $goodsInfo = M('RebateConfig')->where('id=' . I('GET.id', 0))->find();

        $this->assign('goodsInfo', $goodsInfo);
//        $regionList = M('RebateConfig')->where(array('level'=>1))->select();

//        $this->assign('regionList', $regionList);
//        $this->initEditor(); // 编辑器
        $this->display('_rebate_config');
    }
    public function del(){

        M('RebateConfig')->where("id = {$_GET['id']}")->delete();
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn(json_encode($return_arr));

    }
    public function  new3AgentRebateUI(){

        $this->display('agentRebateUI');
    }


    public  function testAgentRebate(){

        $pass = I('pass');

        if($pass !== C('REBATEPASS')){
            $result = array('status'=> -1, 'msg'=> '密码错误');
            $this->ajaxReturn($result);
            return ;
        }
        else
            $result = array('status'=> 1, 'msg'=> '密码正确');

        $this->ajaxReturn($result);


    }

    /**
     * 第三个代理商返利函数
     */
    public function  new3AgentRebate(){
        //验证密码
        $pass = I('pass');

        if($pass !== C('REBATEPASS')){
            $result = array('status'=> -1, 'msg'=> '密码错误');
            $this->ajaxReturn($result);
            return ;
        }

        $logic = new MoneyLogLogic();
        //找到所有代理商
        $agentUserList = M('users')->where(array('user_type'=> 1))->select();
        //找自身返点比例
        $selfRebateRatio = M('config')->where(array('name'=> 'self_rebate_ratio'))->getField('value');
        //找下一级返点比例
        $oneRebateRatio = M('config')->where(array('name'=> 'one_rebate_ratio'))->getField('value');
        //找第二级返点比例
        $twoRebateRatio = M('config')->where(array('name'=> 'two_rebate_ratio'))->getField('value');
        //找第三级返点比例
        $threeRebateRatio = M('config')->where(array('name'=> 'three_rebate_ratio'))->getField('value');
        //遍历所有代理商把其自身销售额加上下三级自身销售额乘上一个固定比例所得结果返利给该用户
        foreach ($agentUserList as $key => $val){
            $rebateMoney = 0;
            $selfMoney = $val['self_month_sales'] * $selfRebateRatio;
            $oneMoney = $val['one_month_sales'] * $oneRebateRatio;
            $twoMoney = $val['two_month_sales'] * $twoRebateRatio;
            $threeMoney = $val['three_month_sales'] * $threeRebateRatio;
            $rebateMoney = $selfMoney + $oneMoney + $twoMoney + $threeMoney;
            M('users')->where(array('user_id'=>$val['user_id']))->setInc('user_money', $rebateMoney);
            M('users')->where(array('user_id'=>$val['user_id']))->setField('self_month_sales', 0);
            M('users')->where(array('user_id'=>$val['user_id']))->setField('one_month_sales', 0);
            M('users')->where(array('user_id'=>$val['user_id']))->setField('two_month_sales', 0);
            M('users')->where(array('user_id'=>$val['user_id']))->setField('three_month_sales', 0);
            $logic->newAddAgentRebateLog($val['user_id'], $rebateMoney, $val['self_month_sales'], $val['one_month_sales'], $val['two_month_sales'], $val['three_month_sales'],$selfRebateRatio,$oneRebateRatio, $twoRebateRatio, $threeRebateRatio);
        }

        $this->ajaxReturn(array('status'=> -1, 'msg' => '返利完成'));

    }


    /**
     * 新的代理商返利函数
     */
    public function newAgentRebate(){
        $logic = new MoneyLogLogic();
        //找到所有代理商
        $agentUserList = M('users')->where(array('user_type'=> 1))->select();
        //找到返利比例rebate_ratio
        $rebateRatio = M('config')->where(array('name'=>'rebate_ratio'))->getField('value');
        //遍历所有代理商把其自身销售额加上下级自身销售额乘上一个固定比例所得结果返利给该用户
        foreach ($agentUserList as $key => $val){
            $sumSales = $val['self_month_sales'] + $val['team_month_sales'];
            $rebateMoney = $sumSales * $rebateRatio;
            M('users')->where(array('user_id'=>$val['user_id']))->setInc('user_money', $rebateMoney);
//            $user_id, $money, $self_month_sales, $team_month_sales, $rebate_ratio
            $logic->addAgentRebateLog($val['user_id'], $rebateMoney, $val['self_month_sales'], $val['team_month_sales'], $rebateRatio);
            //将用户self_month_sales 和team_month_sales 清零
            M('users')->where(array('user_id'=>$val['user_id']))->setField('self_month_sales', 0);
            M('users')->where(array('user_id'=>$val['user_id']))->setField('team_month_sales', 0);
        }
    }







    public function agentRebate(){
        //第一级用户
        $oneUser =  M('users')->where('first_leader is null and  user_type = 1 ')->select();
        //算总销售额
//        var_dump($oneUser);
        foreach($oneUser as  $key => $val){
            //数据初始化
            $this->tree = array();
            $this->rebate = 0; //总销售额返利比例
            $this->selfRebate = 0; //自身销售额返利比例
            $this->rebateMoney = 0; //返利金额
            //找下级代理商加入到tree数组中遍历将tree数组当成队列使用用广度优先遍历下级代理商返利
            $val['user_money'] += $this->rebate11($val);
            //如果下级用户的下级销售额为0则更新用户信息跳出循环
            if($val['team_month_sales'] == 0) {
                $val['self_month_sales'] = 0;
                $val['team_month_sales'] = 0;
              M('users')->save($val);//更新用户信息
                continue;
            }
            //找孩子
            $son = M('users')->where(array('first_leader'=> $val['user_id'], 'user_type'=> 1))->select();
//            var_dump($son);
            if($son) {
                //将孩子加入tree数组不更新用户信息
                $this->sonRebate($son);
                }
                $val['user_money'] += $this->rebateMoney;
                //将销售额置0 一个是自身月销售额self_month_sales一个是下级月销售额team_month_sales
                $val['self_month_sales'] = 0;
                $val['team_month_sales'] = 0;

//                var_dump($this->tree);
                //开始递归
                $this->noticeRebate(0);
                M('users')->save($val);
        }
    }
    //递归调用方法
    public function  noticeRebate($index){
        var_dump($this->tree);
        if(!$this->tree)  return ; //数组为空时说明遍历结束return
        $user = M('users')->where(array('user_id'=> $this->tree[$index]['user_id']))->find();
        //出队
        unset($this->tree[$index]);
        //针对这个index用户返利
        $this->rebate = 0; //总销售额返利比例
        $this->selfRebate = 0; //自身销售额返利比例
        $this->rebateMoney = 0; //返利金额
        $user['user_money'] +=  $this->rebate11($user);
        //剪枝
        if($user['team_month_sales'] == 0) {
              $this->noticeRebate($index+1);
              $user['self_month_sales'] = 0;
              $user['team_month_sales'] = 0;
              M('users')->save($user);//更新用户信息
              return;
        }
        //找孩子
        $son = M('users')->where(array('first_leader'=> $user['user_id'], 'user_type'=> 1))->select();
        if($son) {
            //将孩子加入tree数组不更新用户信息 入队
            $this->sonRebate($son);
        }
        $user['user_money'] += $this->rebateMoney;
        //将销售额置0 一个是自身月销售额self_month_sales一个是下级月销售额team_month_sales
        $user['self_month_sales'] = 0;
        $user['team_month_sales'] = 0;

        //递归
        $this->noticeRebate($index+1);
        //递归完成更新用户信息
        M('users')->save($user);
//        var_dump($this->tree);

    }


    private function returnRebateRatio($money){
        foreach ($this->config as $ke => $v) {
            //找到总销售额满足那一档次
            if ($money > $ke) {
              return $v;
            }
        }
    }

    //返利函数包装
    private function rebate11($user){
        $sumSales = $user['team_month_sales'] + $user['self_month_sales'];
        $this->rebate = $this->returnRebateRatio($sumSales);
        $this->selfRebate = $this->returnRebateRatio($user['self_month_sales']);
        $this->rebateMoney = $sumSales * $this->rebate;
        //更新用户余额
//        $user['user_money'] += $this->selfRebate * $user['self_month_sales'];
        $this->rebateMoney -= $this->rebate * $user['self_month_sales'];
        return  $this->rebate * $user['self_month_sales'];
    }


    //孩子返利包装
    private function  sonRebate($son){
        foreach ($son as $sonk => $sonv) {
            $sonSelfRebate = 0; //自身销售比例
            $sonRebate = 0;//总销售比例
            $sonSumSales = $sonv['self_month_sales'] + $sonv['team_month_sales'];
            //遍历孩子判断下级销售额是否为0若是则减枝
            $sonRebate = $this->returnRebateRatio($sonSumSales);
            $sonRebateMoney = $sonRebate * $sonSumSales;
            $this->rebateMoney -= $sonRebateMoney;
            $this->tree[] = array('user_id' => $sonv['user_id'], 'money' => $sonRebateMoney);
        }
    }

}